/**
 * GPIO中断模式+定时器  模拟解码红外遥控信号NEC协议
 * 解码思路：
 * 1.定时器100us，定时器中断里面tmrcnt++；
 * 2.GPIO中断模式下降沿触发；
 * 3.每个NEC码有33个（1位同步码+32位数据）下降沿；
 * 4.通过检测两个下降宽度判断数据1或0；
 * 5.NEC头9+4.5ms=13500us 大约计数值是135；
 * 6.NEC逻辑1宽度2.25ms=2250us  大约计数值23；
 * 7.NEC逻辑0宽度1.12ms=1120us  大约计数值11；
 * 8.检测到同步码后的32个下降沿脉冲即时数据；
 * 
*/

#include "config.h"
#include "STC32G_Timer.h"
#include "STC32G_GPIO.h"
#include "STC32G_NVIC.h"
#include "STC32G_Exti.h"

#include "app_config.h"
#include "drv_irnec.h"
#include "debug.h"


#if TCFG_DRV_IRNEC_SUPPORT
enum {
    E_IR_STATUS_IDLE=0,     // 等待解码
    E_IR_STATUS_START,      // 开始解码 
    E_IR_STATUS_DONE,       // 解码完成
    E_IR_STATUS_UNKNOW
};

struct ir_nec_t {
    uint8 status;         // 开始接收
    uint8 bit_index;      // 位索引
    uint8 flg_repeat;     // 重复码标记
    uint8 keycode[4];     // 4字节遥控码：用户码+用户码反码+键值码+键值反码
    uint16 timer_cnt;     // 定时器记数值
    uint16 tmrcnt[33];    // 接收到的时间数据
};

static struct ir_nec_t ir_nec = {0};

void ir_nec_driver_init(void)
{
    TIM_InitTypeDef		TIM_InitStructure;
    EXTI_InitTypeDef	Exti_InitStructure;

#if 0
    GPIO_InitTypeDef GPIO_IniStructure;
    GPIO_IniStructure.Pin = GPIO_P1;
    GPIO_IniStructure.Mode = GPIO_OUT_PP;
    GPIO_Inilize(GPIO_P3, &GPIO_IniStructure);
#endif

    // TODO: IR信号输入 外部中断  边沿触发
    P3_MODE_IO_PU(GPIO_Pin_2);		//P3.0~P3.7 设置为准双向口
	P3_PULL_UP_ENABLE(GPIO_Pin_2);    //P3 口内部上拉电阻使能
    Exti_InitStructure.EXTI_Mode      = EXT_MODE_Fall;//中断模式,   EXT_MODE_RiseFall,EXT_MODE_Fall
    Ext_Inilize(EXT_INT0, &Exti_InitStructure);				//初始化
	NVIC_INT0_Init(ENABLE,Priority_1);		//中断使能, ENABLE/DISABLE; 优先级(低到高) Priority_0,Priority_1,Priority_2,Priority_3

    // TODO: IR解码定时器100us
    TIM_InitStructure.TIM_Mode      = TIM_16BitAutoReload;	//指定工作模式,   TIM_16BitAutoReload,TIM_16Bit,TIM_8BitAutoReload,TIM_16BitAutoReloadNoMask
	TIM_InitStructure.TIM_ClkSource = TIM_CLOCK_1T;		//指定时钟源, TIM_CLOCK_1T,TIM_CLOCK_12T,TIM_CLOCK_Ext
	TIM_InitStructure.TIM_ClkOut    = DISABLE;				//是否输出高速脉冲, ENABLE或DISABLE
	TIM_InitStructure.TIM_Value     = (u16)(65536UL - (MAIN_Fosc / 10000UL));			//初值,
	TIM_InitStructure.TIM_PS        = 0;					//8位预分频器(n+1), 0~255
	TIM_InitStructure.TIM_Run       = ENABLE;				//是否初始化后启动定时器, ENABLE或DISABLE
	Timer_Inilize(Timer3,&TIM_InitStructure);				//初始化Timer1	  Timer0,Timer1,Timer2,Timer3,Timer4
	NVIC_Timer3_Init(ENABLE,Priority_2);		//中断使能, ENABLE/DISABLE; 优先级(低到高) Priority_0,Priority_1,Priority_2,Priority_3

    // TODO: 初始化状态
    ir_nec.status = E_IR_STATUS_IDLE;
    ir_nec.bit_index = 0;
    ir_nec.flg_repeat = 0;
    ir_nec.timer_cnt = 0;
}


uint8 ir_nec_driver_decoder(void)
{
    uint8 i,j=0;
    uint8 id=0;
    uint8 _bit=0;
    if (E_IR_STATUS_DONE == ir_nec.status) {
        // log_d("IR bit_index:%d\n", (int)ir_nec.bit_index);
        ir_nec.keycode[0]=0x00;
        ir_nec.keycode[1]=0x00;
        ir_nec.keycode[2]=0x00;
        ir_nec.keycode[3]=0x00;

        #if 0 // for debug
        for (i=0; i<33; i++) {
            log_d("IR [%d]:%d\n", (int)i, (int)ir_nec.tmrcnt[i]);
        }
        #endif

        id=1;   // 第一个索引值是引导码时间，之后是遥控码的脉冲时间
        for (i=0; i<4; i++) {
            // 循环4次解码4字节数据
            for (j=0; j<8; j++) {
                // 解码1个字节数据
                if ((ir_nec.tmrcnt[id]>=8) && (ir_nec.tmrcnt[id]<=15)) { // bit 0
                    _bit = 0;
                } else if ((ir_nec.tmrcnt[id]>=18) && (ir_nec.tmrcnt[id]<=25)) { // bit 1
                    _bit = 1;
                }
                ir_nec.keycode[i] |= (_bit<<j);
                id++;
            }
        }
        // log_d("0x%02X,0x%02X,0x%02X,0x%02X\n", (int)ir_nec.keycode[0], (int)ir_nec.keycode[1], (int)ir_nec.keycode[2], (int)ir_nec.keycode[3]);
        ir_nec.status = E_IR_STATUS_IDLE;
        return E_IR_KEYCODE_VALUE;
    } else if (ir_nec.flg_repeat == 1) {
        // log_d("Repeat 0x%02X,0x%02X,0x%02X,0x%02X\n", (int)ir_nec.keycode[0], (int)ir_nec.keycode[1], (int)ir_nec.keycode[2], (int)ir_nec.keycode[3]);
        ir_nec.flg_repeat = 0;
        return E_IR_KEYCODE_REPEAT;
    }

    return E_IR_KEYCODE_NONE;
}


struct ir_keycode_t ir_nec_driver_keycode(void)
{
    uint8 ret=0;
    struct ir_keycode_t keycode={0};
    ret = ir_nec_driver_decoder();

    // TODO: 过滤指定用户码
    if ((ir_nec.keycode[0] != IR_USER_CODE_A)&&(ir_nec.keycode[0] != IR_USER_CODE_B)) {
        ret = E_IR_KEYCODE_NONE;
    }

    if (E_IR_KEYCODE_NONE == ret) {
        keycode.isvalid = 0;
        keycode.keycode = 0x00;
        keycode.repeat = 0;
    } else if (E_IR_KEYCODE_VALUE == ret) {
        keycode.isvalid = 1;
        keycode.keycode = ir_nec.keycode[2];
        keycode.repeat = 0;
    } else if (E_IR_KEYCODE_REPEAT == ret) {
        keycode.isvalid = 1;
        keycode.keycode = ir_nec.keycode[2];
        keycode.repeat = 1;
    }

    return keycode;
}


void INT0_ISR_Handler (void) interrupt INT0_VECTOR		//进中断时已经清除标志
{
    // TODO: 在此处添加用户代码
    if (E_IR_STATUS_START == ir_nec.status) {
        if ((ir_nec.timer_cnt<120)&&(ir_nec.timer_cnt>100)) {
            // TODO: 接收到重复码
            ir_nec.bit_index=0;
            ir_nec.flg_repeat = 1;
        } else if ((ir_nec.timer_cnt<150)&&(ir_nec.timer_cnt>110)) {
            // TODO: 接收到引导码
            ir_nec.bit_index=0;
        }
        ir_nec.tmrcnt[ir_nec.bit_index] = ir_nec.timer_cnt;
        ir_nec.timer_cnt = 0;
        ir_nec.bit_index++;
        if (33 == ir_nec.bit_index) {
            ir_nec.bit_index = 0;
            ir_nec.timer_cnt = 0;
            ir_nec.status = E_IR_STATUS_DONE;
        }
    } else if (E_IR_STATUS_IDLE == ir_nec.status) {
        // TODO: 第一个下降沿
        ir_nec.status = E_IR_STATUS_START;
        ir_nec.bit_index = 0;
        ir_nec.timer_cnt = 0;
    }

    // P31 = !P31;
}

/**
 * @brief   IR NEC 解码定时器中断100us
*/
void Timer3_ISR_Handler (void) interrupt TMR3_VECTOR		//进中断时已经清除标志
{
	// TODO: 在此处添加用户代码
    // P31 = !P31;
    ir_nec.timer_cnt++;
}
#endif

// 一个NEC码计数值打印
#if 0
IR [0]:134 
IR [1]:23 
IR [2]:11 
IR [3]:11 
IR [4]:12 
IR [5]:11 
IR [6]:11 
IR [7]:11 
IR [8]:10 
IR [9]:23 
IR [10]:11 
IR [11]:22 
IR [12]:23 
IR [13]:22 
IR [14]:23 
IR [15]:22 
IR [16]:23 
IR [17]:11 
IR [18]:23 
IR [19]:22 
IR [20]:22 
IR [21]:11 
IR [22]:11 
IR [23]:22 
IR [24]:23 
IR [25]:22 
IR [26]:11 
IR [27]:12 
IR [28]:11 
IR [29]:22 
IR [30]:23 
IR [31]:11 
IR [32]:11 
#endif